import React, { Component } from 'react';
import {
  Select,
  Form,
  Card,
  Button,
  Row,
  Col,
  Table,
  Divider,
  Tag,
  Input,
  DatePicker,
  Pagination,
  Icon,
} from 'antd';
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;
import BaseComponent from '@/components/BaseComponent';
import { connect } from 'dva';
import moment from 'moment';
import { saveAs } from 'file-saver';

@connect(({ user }) => ({
  // data: risk.riskData,
  currentUser: user.currentUser,
}))
export default class index extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      expand: false,
      data: [],
      total: 0,
      current: 0,
      form: {},
      provinceIdData: [],
      cityIdData: [],
      districtIdData: [],
    };
  }
  cityIdChange = value => {
    const str = value ? this.state.cityIdData.find(item => item.code == value) : '';
    const name = str.name;
    this.setState(
      params => ({
        form: {
          ...params.form,
          cityId: value,
          cityName: name,
        },
      }),
      () => {
        this.getCity({ level: 3, parentCode: value });
      }
    );
  };

  districtIdChange = value => {
    const str = value ? this.state.districtIdData.find(item => item.code == value) : '';
    const name = str.name;
    this.setState(
      params => ({
        form: {
          ...params.form,
          districtId: value,
          districtName: name,
        },
      }),
      () => { }
    );
  };
  institutionNameChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        institutionName: value,
      },
    }));
  };
  screeningYearChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        screeningYear: value,
      },
    }));
  };
  sexChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        sex: value,
      },
    }));
  };



  componentDidMount() {
    this.getDataByPage({});
    this.getCity({ level: 2, parentCode: '34' });
  }
  //查询省
  getCity = param => {
    this.execHttp('plannedFollowUp/getCity', { ...param }).then(resp => {
      if (resp) {
        if (param.level == 1) {
          this.setState({
            provinceIdData: resp.data,
          });
        } else if (param.level == 2) {
          this.setState({
            cityIdData: resp.data,
          });
        } else if (param.level == 3) {
          this.setState({
            districtIdData: resp.data,
          });
        }
      }
    });
  };

  //分页切换
  onChangePagination = (page, pageSize) => {
    this.getDataByPage({
      user: this.props.currentUser.id,
      currentPage: page,
      pageSize: pageSize,
      ...this.state.form,
    });
  };
  onShowSizeChange = (current, pageSize) => {
    if (current === 0) {
      current = 1;
    }
    this.getDataByPage({
      user: this.props.currentUser.id,
      currentPage: current,
      pageSize: pageSize,
      ...this.state.form,
    });
  };

  //分页
  getDataByPage = params => {
    this.execHttp('workReportApi/selList', {
      user: this.props.currentUser.id,
      currentPage: 1,
      pageSize: 10,
      ...params,
    }).then(resp => {
      if (resp.success) {
        this.setState({
          data: resp.data.list,
          total: resp.data.pagination.total,
          current: resp.data.pagination.current,
        });
      }
    });
  };

  //查询
  searchClick = () => {
    this.getDataByPage(this.state.form);
  };

  // 导出
  exportData = () => {
    const hide = this.loadingMessage('正在导出数据，请稍后...');
    this.execHttp('workReportApi/queryAllExportData', {
      user: this.props.currentUser.id,
      ...this.state.form,
    })
      .then(res => {
        hide();
        saveAs(res, '详细数据上报' + '.xlsx');
      })
      .catch(err => {
        hide();
      });
  };

  //重置
  resetClick = () => {
    this.setState(
      () => ({
        form: {},
      }),
      () => {
        this.getDataByPage(this.state.form);
      }
    );
  };
  //展开与否状态切换
  handleToggle = () => {
    const { expand } = this.state;
    this.setState({ expand: !expand });
  };
  DateChange = (date, dateString, fieldName) => {
    const { form } = this.state
    form[fieldName] = dateString
    console.log(date, dateString, fieldName);
    this.setState({
      form: {
        ...form
      }
    })

  }
  formItemBlur = (fieldName) => {

    const { form } = this.state
    if (fieldName == 'ageBegin') {

      if (parseInt(form[fieldName]) > parseInt(form['ageEnd'])) {
        form['ageEnd'] = ''
      }

    } else if (fieldName == 'ageEnd') {
      if (parseInt(form[fieldName]) < parseInt(form['ageBegin'])) {
        form['ageBegin'] = ''
      }
    }    // 内镜诊断开始时间和结束时间限制
    else if (fieldName == 'njzlDateBegin') {
      let begin = new Date(form['njzlDateBegin']).getTime()
      let end = new Date(form['njzlDateEnd']).getTime()

      if (begin > end) {
        form['njzlDateEnd'] = ''
      }
    } else if (fieldName == 'njzlDateEnd') {
      let begin = new Date(form['njzlDateBegin']).getTime()
      let end = new Date(form['njzlDateEnd']).getTime()

      if (begin > end) {
        form['njzlDateBegin'] = ''
      }


    }
    // 统计开始时间和结束时间限制
    else if (fieldName == 'statisticalTimeBegin') {
      let begin = new Date(form['statisticalTimeBegin']).getTime()
      let end = new Date(form['statisticalTimeEnd']).getTime()

      if (begin > end) {
        form['statisticalTimeEnd'] = ''
      }
    } else if (fieldName == 'statisticalTimeEnd') {
      let begin = new Date(form['statisticalTimeBegin']).getTime()
      let end = new Date(form['statisticalTimeEnd']).getTime()

      if (begin > end) {
        form['statisticalTimeBegin'] = ''
      }


    }
    this.setState({
      form: {
        ...form
      }
    })
  }
  formItemChange = (e, fieldName, dateString) => {

    const { form } = this.state
    let value;

    if (e.target) {
      console.log(e.target.value);
      value = e.target.value
    } else {
      // console.log(new Date(e));
      console.log(typeof e);
      if (typeof e == 'object') {
        console.log(dateString, "dateString");
        value = dateString
      } else value = e

    }

    form[fieldName] = value
    // 开始年龄段和结束年龄段限制

    // console.log(new Date(e).getTime());

    this.setState({
      form: {
        ...form
      }
    })


  }
  render() {
    const columns = [
      {
        title: '省名称',
        dataIndex: 'province',
        key: 'province',
        width: 100,
      },
      {
        title: '市名称',
        dataIndex: 'city',
        key: 'city',
        width: 100,
      },
      {
        title: '区县名称',
        dataIndex: 'district',
        key: 'district',
        width: 100,
      },
      {
        title: '上报机构',
        dataIndex: 'institution',
        key: 'institution',
        width: 200,
      },
      {
        title: '合计',
        children: [
          {
            title: '任务数',
            dataIndex: 'year_task_volume',
            key: 'year_task_volume',
            width: 100,
          },
          {
            title: '自测表',
            dataIndex: 'zchj',
            key: 'zchj',
            width: 100,
          },
          {
            title: '完成数',
            dataIndex: 'wchj',
            key: 'wchj',

            width: 100,
          },
          {
            title: '完成率(%)',
            dataIndex: 'wclhj',
            key: 'wclhj',

            width: 100,
            render: (data) => (
              <span style={{ color: data < 90 ? 'red' : '#1890FF' }} > {data}</span>
            ),
          },
          {
            title: '病例数',
            dataIndex: 'blhj',
            key: 'blhj',

            width: 100,
          },
          {
            title: '检出率(%)',
            dataIndex: 'jclhj',
            key: 'jclhj',
            render: (data) => (
              <span style={{ color: data < 3 ? 'red' : '#1890FF' }} > {data}</span>
            ),
            width: 100,
          },
          {
            title: '早诊数',
            dataIndex: 'zzhj',
            key: 'zzhj',

            width: 100,
          },
          {
            title: '早诊率(%)',
            dataIndex: 'zzlhj',
            key: 'zzlhj',
            render: (data) => (
              <span style={{ color: data < 30 ? 'red' : '#1890FF' }} > {data}</span>
            ),
            width: 100,
          },
          {
            title: '治疗数',
            dataIndex: 'zlhj',
            key: 'zlhj',

            width: 100,
          },
          {
            title: '治疗率(%)',
            dataIndex: 'zllhj',
            key: 'zllhj',

            width: 100,
            render: (data) => (
              <span style={{ color: data < 70 ? 'red' : '#1890FF' }} > {data}</span>
            ),
          },
        ],
      },
      {
        title: '初筛',
        children: [
          {
            title: '完成数',
            dataIndex: 'wcCs',
            key: 'wcCs',
            width: 100,
          },
          {
            title: '病例数',
            dataIndex: 'blCs',
            key: 'blCs',
            width: 100,
          },
          {
            title: '检出率(%)',
            dataIndex: 'jclCs',
            key: 'jclCs',
            width: 100,
            render: (data) => (
              <span style={{ color: data < 3 ? 'red' : '#1890FF' }} > {data}</span>
            ),
          },
          {
            title: '早诊数',
            dataIndex: 'zzCs',
            key: 'zzCs',
            width: 100,
          },
          {
            title: '早诊率(%)',
            dataIndex: 'zzlCs',
            key: 'zzlCs',
            width: 100,
            render: (data) => (
              <span style={{ color: data < 30 ? 'red' : '#1890FF' }} > {data}</span>
            ),
          },
          {
            title: '治疗数',
            dataIndex: 'zlCs',
            key: 'zlCs',
            width: 100,
          },
          {
            title: '治疗率(%)',
            dataIndex: 'zllCs',
            key: 'zllCs',
            width: 100,
            render: (data) => (
              <span style={{ color: data < 70 ? 'red' : '#1890FF' }} > {data}</span>
            ),
          },
        ],
      },
      {
        title: '随访',
        children: [
          {
            title: '应随访数',
            dataIndex: 'ySfNum',
            key: 'ySfNum',
            width: 100,
          },
          {
            title: '随访数',
            dataIndex: 'sfNum',
            key: 'sfNum',
            width: 100,
          },
          {
            title: '随访率(%)',
            dataIndex: 'sfl',
            key: 'sfl',
            width: 100,
          },
          {
            title: '病例数',
            dataIndex: 'blSf',
            key: 'blSf',
            width: 100,
          },
          {
            title: '检出率(%)',
            dataIndex: 'jclSf',
            key: 'jclSf',
            width: 100,
            render: (data) => (
              <span style={{ color: data < 3 ? 'red' : '#1890FF' }} > {data}</span>
            ),
          },
          {
            title: '早诊数',
            dataIndex: 'zzSf',
            key: 'zzSf',
            width: 100,
          },
          {
            title: '早诊率(%)',
            dataIndex: 'zzlSf',
            key: 'zzlSf',
            width: 100,
            render: (data) => (
              <span style={{ color: data < 30 ? 'red' : '#1890FF' }} > {data}</span>
            ),
          },
          {
            title: '治疗数',
            dataIndex: 'zlSf',
            key: 'zlSf',
            width: 100,
          },
          {
            title: '治疗率(%)',
            dataIndex: 'zllSf',
            key: 'zllSf',
            width: 100,
            render: (data) => (
              <span style={{ color: data < 70 ? 'red' : '#1890FF' }} > {data}</span>
            ),
          },
        ],
      },
    ];

    const { data, total, current } = this.state;
    let bwCodeOptions = [
      { value: 'sg', label: 'sg' },
      { value: 'wb', label: 'wb' },
      { value: 'bm', label: 'bm' },
      { value: 'sezc', label: 'sezc' },
    ]
    return (
      <div>
        <Card size="small" style={{ width: '100%' }} bordered={true} title={'工作报表'}>
          <Form layout="horizontal">
            <Row gutter={16}>
              <Col span={6}>
                <Form.Item>
                  <Select
                    allowClear
                    value={this.state.form.cityId}
                    onChange={this.cityIdChange}
                    placeholder="请选择所属城市"
                  >
                    {this.state.cityIdData.map(item => (
                      <Select.Option key={item.code}>{item.name}</Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item>
                  <Select
                    allowClear
                    value={this.state.form.districtId}
                    onChange={this.districtIdChange}
                    placeholder="请选择所属区/县"
                  >
                    {this.state.districtIdData.map(item => (
                      <Select.Option key={item.code}>{item.name}</Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item>
                  <Input
                    placeholder="机构名称"
                    value={this.state.form.institutionName}
                    onChange={this.institutionNameChange}
                  />
                </Form.Item>
              </Col>
              <Col span={6} style={{ textAlign: 'center' }}>
                <Button type="primary" onClick={this.searchClick}>
                  查询
                </Button>
                <Button type="primary" style={{ marginLeft: '10px' }} onClick={this.exportData}>
                  导出
                </Button>
                <Button onClick={this.resetClick} style={{ marginLeft: '10px' }}>
                  重置
                </Button>
                <a style={{ marginLeft: 8, fontSize: 12 }} onClick={this.handleToggle}>
                  {this.state.expand ? '折叠' : '展开'}
                  <Icon type={this.state.expand ? 'up' : 'down'} />
                </a>
              </Col>
            </Row>
            <Row gutter={16} style={{ display: this.state.expand ? 'block' : 'none' }}>
            <Col span={6}>
                <Form.Item>
                  <Input
                    placeholder="请输入筛查年度"
                    value={this.state.form.screeningYear}
                    onChange={this.screeningYearChange}
                  />
                </Form.Item>
              </Col>


              <Col span={6}>
                <Form.Item>
                  <Input
                    placeholder="性别"
                    value={this.state.form.sex}
                    onChange={this.sexChange}
                  />
                </Form.Item>
              </Col>

              <Col span={6}>
                <Form.Item>
                  <Col span={11}>
                    <Input
                      placeholder="年龄段开始"
                      value={this.state.form.ageBegin}
                      // ageEnd
                      onChange={(e) => this.formItemChange(e, 'ageBegin')}
                      onBlur={() => this.formItemBlur('ageBegin')}
                    />
                  </Col>
                  <Col span={2} style={{ display: 'flex', justifyContent: 'center' }}>-</Col>

                  <Col span={11} >
                    <Input
                      placeholder="年龄段结束"
                      value={this.state.form.ageEnd}
                      // ageEnd
                      onBlur={() => this.formItemBlur('ageEnd')}
                      onChange={(e) => this.formItemChange(e, 'ageEnd')}
                    />
                  </Col>

                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item>

                  <Select
                    placeholder="部位"
                    value={this.state.form.bwCode}
                    onChange={(e) => this.formItemChange(e, 'bwCode')}
                  >
                    {bwCodeOptions.map(item => (<Select.Option key={item.value}>{item.label}</Select.Option>))}
                  </Select>
                </Form.Item>
              </Col>
            </Row>          
            <Row gutter={16} style={{ display: this.state.expand ? 'block' : 'none' }}>              
              <Col span={6}>
                <Form.Item>
                  <Col span={11}>
                    {/* <DatePicker placeholder="确诊开始日期"
                      onChange={(e) => this.formItemChange(e, 'njzlDateBegin')}
                      value={this.state.form.njzlDateBegin}
                      format="YYYY-MM-DD" /> */}
                    <DatePicker placeholder="确诊开始日期"
                      onChange={(e, dateString) => this.formItemChange(e, 'njzlDateBegin', dateString)}

                      value={this.state.form.njzlDateBegin === undefined ? this.state.form.njzlDateBegin : moment(this.state.form.njzlDateBegin, 'YYYY-MM-DD')}

                      // value={this.state.form.njzlDateBegin}
                      format="YYYY-MM-DD" />
                  </Col>
                  <Col span={2} style={{ display: 'flex', justifyContent: 'center' }}>-</Col>

                  <Col span={11} >

                    <DatePicker placeholder="确诊结束日期"
                      value={this.state.form.njzlDateEnd === undefined ? this.state.form.njzlDateEnd : moment(this.state.form.njzlDateEnd, 'YYYY-MM-DD')}

                      onChange={(e, dateString) => this.formItemChange(e, 'njzlDateEnd', dateString)}
                      format="YYYY-MM-DD" />
                  </Col>
                </Form.Item>
              </Col>

              <Col span={6}>
                <Form.Item>
                  <Col span={11}>
                    <DatePicker placeholder="统计开始日期"
                      onChange={(e, dateString) => this.formItemChange(e, 'statisticalTimeBegin', dateString)}
                      value={this.state.form.statisticalTimeBegin === undefined ? this.state.form.statisticalTimeBegin : moment(this.state.form.statisticalTimeBegin, 'YYYY-MM-DD')}

                      format="YYYY-MM-DD" />
                  </Col>
                  <Col span={2} style={{ display: 'flex', justifyContent: 'center' }}>-</Col>

                  <Col span={11} >

                    <DatePicker placeholder="统计开始日期"
                      value={this.state.form.statisticalTimeEnd === undefined ? this.state.form.statisticalTimeEnd : moment(this.state.form.statisticalTimeEnd, 'YYYY-MM-DD')}

                      onChange={(e, dateString) => this.formItemChange(e, 'statisticalTimeEnd', dateString)}
                      format="YYYY-MM-DD" />
                  </Col>
                </Form.Item>
              </Col>
            </Row>

          </Form>
          <Table
            columns={columns}
            dataSource={data}
            rowKey="id"
            pagination={false}
            bordered
            scroll={{ x: 'calc(700px + 50%)', y: 500 }}
            size="small"
            style={{marginTop:'20px'}}
          />
          <div
            style={{
              marginTop: '20px',
              display: 'flex',
              flexDirection: 'row-reverse',
            }}
          >
            <Pagination
              showSizeChanger={true}
              showQuickJumper
              onChange={this.onChangePagination}
              onShowSizeChange={this.onShowSizeChange}
              defaultCurrent={1}
              total={total}
              showTotal={total => `总共 ${total} 条`}
            />
          </div>
        </Card>
      </div>
    );
  }
}
